
#include <stdlib.h>
#include <stdio.h>
#include "addrcheck.h"

void init_addr_list(struct addr_list_t *list)
{
	list->head = NULL;
	list->tail = NULL;
	list->num = 0;
}

void clear_addr_list(struct addr_list_t *list)
{
	struct addr_node_t *p;
	while(list->head)
	{
		p = list->head;
		list->head = list->head->next;
		free(p);
	}
	list->tail = NULL;
	list->num = 0;
}

int add_addr_list(struct addr_list_t *list, unsigned long addr_start, unsigned long addr_end, unsigned short port_start, unsigned short port_end, int flag)
{
	struct addr_node_t *newNode = (struct addr_node_t *)malloc(sizeof(struct addr_node_t));
	if(NULL == newNode)
		return -1;
	newNode->addr_start = addr_start;
	newNode->addr_end = addr_end;
	newNode->port_start = port_start;
	newNode->port_end = port_end;
	newNode->flag = flag;
	newNode->next = NULL;
	
	if(NULL == list->head)
	{
		list->tail = list->head = newNode;
	}
	else
	{
		list->tail->next = newNode;
		list->tail = newNode;
	}
	list->num++;
	return 0;
}

struct addr_node_t *find_addr_list(struct addr_list_t *list, unsigned long addr, unsigned short port)
{
	struct addr_node_t *p = list->head;
	while(p)
	{
		if(0 == p->flag)
		{
			if(addr >= p->addr_start && addr <= p->addr_end)
				return p;
		}
		else if(1 == p->flag)
		{
			if(port >= p->port_start && port <= p->port_end)
				return p;
		}
		else
		{
			if(addr >= p->addr_start && addr <= p->addr_end && port >= p->port_start && port <= p->port_end)
				return p;
		}
		p = p->next;
	}
	return NULL;
}

int print_addr_list(struct addr_list_t *list)
{
	struct addr_node_t *p = list->head;
	while(p)
	{
		printf("addr_start=%08x, addr_end=%08x, port_start=%u, port_end=%u\n", p->addr_start, p->addr_end, p->port_start, p->port_end, p->flag);
		p = p->next;
	}
	return list->num;
}

